package com.digital.herbarium.Controller;
import com.digital.herbarium.Entity.ResponseResult;
import com.digital.herbarium.Interceptor.ZipSizeInterceptor;
import com.digital.herbarium.service.UploadService;
import com.digital.herbarium.service.ZipService;
import net.lingala.zip4j.core.ZipFile;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/upload")
public class ImageController {
    @Autowired
    private ZipService zipService;

    @Autowired
    private UploadService uploadService;
    @Value("${static.url}")
    private String IMAGES_DIR;
    @Value("${static.maxSize}")
    private Integer maxSize;

    @Autowired
    private ZipSizeInterceptor zipSizeInterceptor;

    @PostMapping("/upload_images")
    public ResponseResult uploadImages(@RequestParam(value = "watermark",defaultValue = "0",required = false)  Integer watermark,
                                       @RequestParam(value = "type",defaultValue = "0",required = false)  Integer type,
                                       @RequestParam(value = "video",defaultValue = "0",required = false)  Integer video,
                                       @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        // 检查zip包大小
        if (file.getSize() > maxSize) {
            return ResponseResult.FAILED().setData("zip包超过50M");
        }

        System.out.println("*******size"+file.getSize() );

        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf('.') + 1);
        System.out.println("filename***"+filename);
        System.out.println("*****extension"+extension);
        if (extension.toLowerCase().equals("jpg") || extension.toLowerCase().equals("png") || extension.toLowerCase().equals("jpeg")
                || extension.toLowerCase().equals("zip") || extension.toLowerCase().equals("mp4")) {
            if (extension.equals("zip")) {

                File file1 = new File(IMAGES_DIR + File.separator + filename);
                //上传文件到服务器/opt/目录下
                //File file1 = new File("E:/zip/" + entity.getValue()+".zip");
                FileUtils.writeByteArrayToFile(file1,file.getBytes());

                ZipFile zipFile = new ZipFile(file1);
                //给的vr是gbk，如果这里，你上传的zip包为utf-8，那么这里改为utf-8
                zipFile.setFileNameCharset("gbk");

                String path= IMAGES_DIR + File.separator + "zip";
                String targetPATH = IMAGES_DIR = File.separator + "image" ;
                if(type == 4){
                    path +=  File.separator + "atlas";
                    targetPATH += File.separator + "atlas";
                }else if(type == 5){
                    path +=  File.separator + "dna";
                    targetPATH += File.separator + "dna";
                }else if(type == 6){
                    path += File.separator + "aboutus";
                    targetPATH += File.separator + "aboutus";
                }else if(type == 7){
                    path +=  File.separator + "popular";
                    targetPATH += File.separator + "popular";
                }
                //解压到指定目录
                zipFile.extractAll(path);
                List<File> allFile = new ArrayList<>();
                zipService.getAllFile(new File(path),allFile);


                System.out.println("allFile****"+allFile.size());
                zipService.deleteFileByIO(targetPATH);
                for (File imageFile : allFile){
                    uploadService.uploadImageMove(imageFile.getAbsolutePath(),targetPATH,
                            imageFile.getName(),watermark,type,video);
                }

                //然后删除
                zipService.deleteFileByIO(path);
                if(file1.exists()){
                    file1.delete();
                }


//                String zipFilename = IMAGES_DIR + File.separator+ filename;
//                System.out.println("IMAGES_DIR******:"+zipFilename);
//                try {
//                    file.transferTo(new File(zipFilename));
//                    zipService.unzipImages(zipFilename);
//                    //zipService.unzip(zipFilename);
//                    File[] imageFiles = new File(zipFilename).listFiles();
//                    for (File imageFile : imageFiles) {
//                        uploadService.uploadImage(file, imageFile.getName(),watermark,type,video);
//                    }
//                    return ResponseResult.SUCCESS().setData("上传成功");
//                } catch (Exception e) {
//                    // 处理异常
//                    throw new CustomException(400, e.getMessage());
//                } finally {
//                    // 删除zip文件和解压后的图片文件
////                    new File(zipFilename).delete();
////                    File[] imageFiles = new File(zipFilename).listFiles();
////                    for (File imageFile : imageFiles) {
////                        imageFile.delete();
////                    }
//                }
            }
            if (extension.toLowerCase().equals("jpg") || extension.toLowerCase().equals("png") || extension.toLowerCase().equals("jpeg")
                    || extension.toLowerCase().equals("mp4")) {
                String imgUrl = uploadService.uploadImage(file, filename, watermark, type,video);
                return ResponseResult.SUCCESS().setData(imgUrl);
            }


        } else {
            return ResponseResult.FAILED().setData("文件格式错误，不是zip，jpg,png,jpeg格式");
        }

        return  ResponseResult.SUCCESS().setData("上传成功");
    }


    @PostMapping("/upload_popular")
    public ResponseResult upload_popular(@RequestParam(value = "id",defaultValue = "0",required = false)  Integer id,
                                       @RequestParam(value = "type",defaultValue = "0",required = false)  Integer type,
                                       @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        if(id == 0){
            return ResponseResult.FAILED().setData("缺少id");
        }
        if(type == 0){
            return ResponseResult.FAILED().setData("缺少type");
        }
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf('.') + 1);
        if (extension.toLowerCase().equals("jpg") || extension.toLowerCase().equals("png") ||
                extension.toLowerCase().equals("jpeg")) {

                String imgUrl = uploadService.uploadPopularImage(file, filename, id, type);
                return ResponseResult.SUCCESS().setData(imgUrl);



        } else {
            return ResponseResult.FAILED().setData("文件格式错误，不是jpg,png,jpeg格式");
        }

    }
}